<template>
  <section>
    <!--工具栏：关键字查询 + 添加-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">
        <el-form-item>
          <el-button v-perm="'productClassify/add'" type="primary" @click="handleAdd">新增分类</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--显示列表-->
    <div>
      <el-table :data="classifyLists" style="width: 100%" row-key="id" border>
        <el-table-column prop="id" label="ID" width="180">
        </el-table-column>

        <el-table-column prop="pictureAddress" label="图标" width="180">
          <template slot-scope="{row}">
            <el-image :src="row.pictureAddress"></el-image>
          </template>
        </el-table-column>

        <el-table-column prop="productClassifyName" label="产品分类名">
        </el-table-column>
        <el-table-column label="操作">
          <template scope="scope">
            <el-button v-perm="'productClassify/update'" type="text" size="small" @click="handleEdit(scope.$index, scope.row)"><i class="el-icon-edit-outline"/>编辑</el-button>
            <el-button v-perm="'productClassify/del'" type="text" size="small" @click="handleDel(scope.$index, scope.row)"><i class="el-icon-delete"/>删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog title="编辑" :visible.sync="editFormVisible" :close-on-click-modal="false">

      <el-form :model="editForm" :label-position="labelPosition" label-width="80px" :rules="editFormRules" ref="editForm">
        <el-form-item label="上级菜单">
          <el-cascader v-model="editForm.parentId" :options="classifyLists"
                       :props="{
                checkStrictly: true,
                label: 'productClassifyName',
                value: 'id'
              }"
                       clearable>
          </el-cascader>
        </el-form-item>
        <el-form-item label="分类名" prop="productClassifyName">
          <el-input v-model="editForm.productClassifyName" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item prop="pictureAddress" label="图标" width="130" sortable>
            <el-image :src="editForm.pictureAddress"></el-image>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="editFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>

    <!--新增界面-->
    <el-dialog title="新增" :visible.sync="addFormVisible" :close-on-click-modal="false">

      <el-form :model="addForm" :label-position="labelPosition" label-width="80px" :rules="addFormRules" ref="addForm">
        <el-form-item label="父级分类"  prop="parentId">
          <el-select v-model="addForm.parentId" placeholder="请选择">
            <el-option v-for="item in parentIds"
                       :label="item.productClassifyName"
                       :value="item.id">
              <span style="float: left">{{ item.productClassifyName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.id }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分类名"  prop="productClassifyName">
          <el-input v-model="addForm.productClassifyName" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="图标">
          <el-upload
              class="upload-demo"
              name="file"
              :action="this.$uploadURL"
              :on-remove="handleFileRemove"
              :on-success="handleFileUpload"
              :on-exceed="handleFileExceed"
              :file-list="fileList"
              :limit=1
              accept=".jpg,.png,.gif"
              list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传指定类型图片文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="addFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>
export default {
  data() {
    return {
      //1.分页查询的相关数据
      classifyLists: [],
      listLoading: false, //列表的加载框
      //2.高级查询相关数据
      keyword: '',
      //3.批量删除的相关数据
      sels: [],//列表选中列
      //4.添加或修改的相关数据
      title: '',          //标题
      // saveFormVisible: false,//控制对话框是都显示，默认为false
      // saveLoading: false, //加载框
      // saveFormRules: { // 表单项验证
      // },


      //3 编辑界面数据
      editFormVisible: false,//新增界面是否显示-->
      editLoading: false,
      editFormRules: {},
      editForm: {
        id: '',
        pictureAddress: '',
        productclassifyName: '',
        parentId: '',
      },

      //4新增界面数据
      addFormVisible: false,//新增界面是否显示-->
      addLoading: false,
      addFormRules: {
        // username: [
        //  {required: true, message: '请输入用户名', trigger: 'blur'}-->
        //  ]
      },
      addForm: {
        id: null,
        pictureAddress: '',
        productClassifyName: '',
        parentId: null,
      },
      parentIds: [],
      fileList: [], //minio用
      labelPosition: 'left',
    }
  },
  methods: {
    //1.分页查询 - 获取部门列表
    getclassifyLists() {
      // let para = {
      //   currentPage: this.currentPage,
      //   pageSize: this.pageSize,
      //   keyword: this.keyword
      // };
      this.listLoading = true;//显示加载框
      this.$http.get("/productClassify/prodTree").then(res => {
        this.classifyLists = res.data;//显示当前页分页数据
        this.totals = res.data.total;//计算分页栏
        this.listLoading = false;//关闭加载框
      }).catch(res => {
        this.$message.warning("系统繁忙，请稍后重试!!!")
      })
    },
    //2查询全部
    getAll() {
      this.$http.get("/productClassify").then(res => {
        this.parentIds = res.data;
      })
    },


    //4.删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => { //点确认框的确认按钮
        this.listLoading = true;
        this.$http.delete("/productClassify/" + row.id).then(res => {
          if (res.data.success) {
            this.getclassifyLists();
          } else {
            this.$message.warning("系统繁忙，请稍后重试!!!");
          }
          this.listLoading = false;
        }).catch(res => {
          this.$message.warning("系统繁忙，请稍后重试!!!");
        })
      }).catch(() => {
      });
    },

    //5.选项改变时触发
    selsChange: function (sels) {
      //将选中的所有对象【集合】赋值给模型数据sels
      this.sels = sels;
    },

    //6.批量删除
    batchRemove: function () {
      //获取选中对象的id
    },

    //7.显示编辑界面
    handleEdit: function (index, row) {
      //防止多个引用指向同一个对象
      this.editForm = Object.assign({}, row);
      this.getclassifyLists();
      //显示对话框
      this.editFormVisible = true;
    },

    //8.显示新增界面
    handleAdd: function () {
      this.addForm = {};
      //重置
      this.getAll();
      this.addFormVisible = true;
    },

    //8编辑数据
    editSubmit: function () {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.editLoading = true;
            let para = Object.assign( {}, this.editForm);
            para.parentId= para.parentId.slice(-1)[0]
            console.log(para)

            // para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
             this.$http.put("/productClassify", para).then(res => {
              if (res.data.success) {
                this.$message({
                  message: '数据编辑提交成功',
                  type: 'success'
                });
                this.$refs['editForm'].resetFields();
              } else {
                this.$message.warning("系统繁忙，请稍后重试!!!");
              }
              this.editLoading = false;
              this.editFormVisible = false;
              this.getclassifyLists();
            });
          });
        }
      });
    },


    //9.增加数据
    addSubmit: function () {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.addLoading = true;
            let para = Object.assign({}, this.addForm);
            this.$http.put("/productClassify", para).then(res => {
              if (res.data.success) {
                this.$message({
                  message: '数据新增添加成功',
                  type: 'success'
                });
                this.$refs['addForm'].resetFields();
              } else {
                this.$message.warning("系统繁忙，请稍后重试!!!");
              }
              this.addLoading = false;
              this.addFormVisible = false;
              this.getclassifyLists();
            });
          });
        }
      });
    },


    //文件删除时的回调-->
    handleFileRemove(file, fileList) {
      //正式删除-->
      var fileName = null;
      if (file.response) {  //上传图片的时候点了删除-->
        fileName = file.response.resultObj;
      } else {  //点击修改回显的图片，点了删除-->
        fileName = file.url;
      }
      //为了方便参数传递,需要转换路径写法,把/替换为_-->
      fileName = fileName.replaceAll("/", "_");
      //发送请求-->
      this.$http.delete("/minio/" + fileName).then(res => {
        if (res.data.success) {
          this.$message.success("删除成功");
          this.fileList = [];
          this.addForm.pictureAddress = "";
        } else {
          this.$message.warning("删除失败");
        }
      })
    },

    //文件上传成功之后的回调
    handleFileUpload(response) {
      if (response.success) {
        this.addForm.pictureAddress = response.resultObj;
      }
    },
    //上传超过数量的回调-->
    handleFileExceed() {
      this.$message.error("不能上传多张图片");
    },
  },




  mounted() {
    this.getclassifyLists();
  }
}

</script>

<style scoped>
</style>